<template>
  <form-panel :form="data.form" :submitUrl="data.submitUrl" ref="formPanelRef" @update="update"
              :queryUrl="data.queryUrl" :id="data.id" class="bikeForm" :submit-before="submitBefore"
              :form-title="data.formTitle">
    <el-form-item
        label="单车名称"
        :rules="[
          { required: true, message: '请输入单车名称', trigger: 'blur' }
        ]"
        prop="name"
    >
      <v-input v-model="data.form.name" placeholder="请输入单车名称" isShowCounter :width="data.width"
      />
    </el-form-item>
    <el-form-item
        label="价格"
        :rules="[{ required: true, message: '请输入价格', trigger: 'blur' }]"
        prop="price"
    >
      <v-input v-model="data.form.price" type="number" placeholder="请输入价格" :width="data.width"/>
    </el-form-item>
    <el-form-item
        label="单车类型"
        :rules="[{ required: true, message: '请选择单车类型', trigger: 'blur' }]"
        prop="bikeType"
    >
      <v-select v-model="data.form.bikeType" :selectOptions="bikeTypeSelectOptions" placeholder="请选择单车类型"
                :width="data.width"/>
    </el-form-item>
    <el-form-item
        label="上市时间"
        :rules="[{ required: true, message: '请选择上市时间', trigger: 'blur' }]"
        prop="marketTime"
    >
      <v-date-picker v-model:dataValue="data.form.marketTime" placeholder="请选择上市时间" :is-picker="false"
                     type="year" format="YYYY" :width="data.width" valueFormat="YYYY"/>
    </el-form-item>
    <el-form-item
        label="品牌"
        :rules="[{ required: true, message: '请选择品牌', trigger: 'blur' }]"
        prop="marketTime"
    >
      <v-select v-model="data.form.brandId" :selectOptions="data.brandSelectOptions" placeholder="请选择品牌" filterable
                remote @remoteMethod="remoteMethod" :width="data.width"/>
    </el-form-item>
    <el-form-item
        label="标签"
    >
      <v-select v-model="data.form.bikeTags" :selectOptions="bikeTagsSelectOptions" placeholder="请选择标签" multiple
                :width="data.width"/>
    </el-form-item>
    <el-form-item
        label="图片"
        :rules="[{ required: true, message: '请上传图片', trigger: 'blur' }]"
        prop="img"
        :style="{width: '100%'}"
    >
      <v-upload v-model="data.form.img"/>
    </el-form-item>
    <el-form-item
        label="车体部分"
        :style="{width: '100%'}"
        :rules="[{ required: true, message: '请输入车体部分参数', trigger: 'blur' }]"
        class="no-flex"
    >
      <div class="box">
        <v-button text="新增" type="primary" @click="addParams('bikeBody')"/>
        <div class="bottom">
          <div v-for="(item,index) in data.bikeBodyParams" :key="index" class="paramsInput">
            <v-select :width="150" :select-options="paramsOptions" v-model="item.name"/>
            <v-input :width="250" v-model="item.content" is-show-counter/>
            <v-button text="删除" type="danger" v-show="data.bikeBodyParams.length > 1"
                      @click="deleteParams(item.uid,'bikeBody')" style="'margin': '0 5px'"/>
          </div>
        </div>
      </div>
    </el-form-item>
    <el-form-item
        label="轮组系统"
        :style="{width: '100%'}"
        :rules="[{ required: true, message: '请输入轮组系统参数', trigger: 'blur' }]"
        class="no-flex"
    >
      <div class="box">
        <v-button text="新增" type="primary" @click="addParams('wheelGroup')"/>
        <div class="bottom">
          <div v-for="(item,index) in data.wheelGroupParams" :key="index" class="paramsInput">
            <v-select :width="150" :select-options="paramsOptions" v-model="item.name"/>
            <v-input :width="250" v-model="item.content" is-show-counter/>
            <v-button text="删除" type="danger" v-show="data.wheelGroupParams.length > 1"
                      @click="deleteParams(item.uid,'wheelGroup')" style="'margin': '0 5px'"/>
          </div>
        </div>
      </div>
    </el-form-item>
    <el-form-item
        label="变速传动系统"
        :style="{width: '100%'}"
        :rules="[{ required: true, message: '请输入变速传动系统', trigger: 'blur' }]"
        class="no-flex"
    >
      <div class="box">
        <v-button text="新增" type="primary" @click="addParams('variableSpeed')"/>
        <div class="bottom">
          <div v-for="(item,index) in data.variableSpeedParams" :key="index" class="paramsInput">
            <v-select :width="150" :select-options="paramsOptions" v-model="item.name"/>
            <v-input :width="250" v-model="item.content" is-show-counter/>
            <v-button text="删除" type="danger" v-show="data.variableSpeedParams.length > 1"
                      @click="deleteParams(item.uid,'variableSpeed')" style="'margin': '0 5px'"/>
          </div>
        </div>
      </div>
    </el-form-item>
    <el-form-item
        label="组件参数"
        :style="{width: '100%'}"
        :rules="[{ required: true, message: '请输入组件参数', trigger: 'blur' }]"
        class="no-flex"
    >
      <div class="box">
        <v-button text="新增" type="primary" @click="addParams('assembly')"/>
        <div class="bottom">
          <div v-for="(item,index) in data.assemblyParams" :key="index" class="paramsInput">
            <v-select :width="150" :select-options="paramsOptions" v-model="item.name"/>
            <v-input :width="250" v-model="item.content" is-show-counter/>
            <v-button text="删除" type="danger" v-show="data.assemblyParams.length > 1"
                      @click="deleteParams(item.uid,'assembly')" style="'margin': '0 5px'"/>
          </div>
        </div>
      </div>
    </el-form-item>
  </form-panel>
</template>

<script lang="ts" setup>
import {reactive, onMounted, ref, watch, inject, computed} from 'vue'
import {useRoute} from 'vue-router'
import {bikeTypeSelectOptions, paramsOptions, bikeTagsSelectOptions} from './selectOptions'
import {getBrandListApi} from "@/api/brand";
import {cloneDeep} from "lodash";

let $message: any = inject('$message')
const $route = useRoute();
const paramsTemplate = [
  {
    name: '',
    content: '',
    uid: Math.random().toString().slice(15)
  }
]
const data = reactive({
  form: {
    name: '',
    marketTime: '',
    brandId: '',
    price: '',
    bikeType: '',
    img: '',
    // //车身部分参数
    // bikeBody: '',
    // //轮组系统参数
    // wheelGroup: '',
    // //变速传动系统参数
    // variableSpeedTransmission: '',
    // //组件参数
    // assembly: '',
    detailParams: '',
    bikeTags: []
  },
  bikeBodyParams: cloneDeep(paramsTemplate),
  wheelGroupParams: cloneDeep(paramsTemplate),
  variableSpeedParams: cloneDeep(paramsTemplate),
  assemblyParams: cloneDeep(paramsTemplate),
  id: '',
  submitUrl: '',
  formTitle: '新增单车',
  userId: undefined,
  mode: '',
  queryUrl: '/api/bike/getDetail',
  brandSelectOptions: [],
  width: 290,
})
const formPanelRef = ref()

// onActivated(()=>{
//   // getBrandList()
//   const {id} = $route.query
//   if (id === undefined) {
//     data.mode = 'create'
//     data.submitUrl = '/api/bike/add'
//     data.formTitle = '新增单车'
//   } else {
//     data.mode = 'update'
//     data.id = id as string;
//     data.submitUrl = '/api/bike/update'
//     data.formTitle = '编辑单车'
//     formPanelRef.value.getData({
//       id
//     })
//   }
// })

onMounted(() => {
  getBrandList()
  const {id} = $route.query
  if (id === undefined) {
    data.mode = 'create'
    data.submitUrl = '/api/bike/add'
    data.formTitle = '新增单车'
  } else {
    data.mode = 'update'
    data.id = id as string;
    data.submitUrl = '/api/bike/update'
    data.formTitle = '编辑单车'
    formPanelRef.value.getData({
      id
    })
  }
})

const update = (params) => {
  Object.keys(params).forEach(key => {
    if (data.form[key] !== undefined) {
      if (key !== 'detailParams' || 'bikeTags') {
        data.form[key] = params[key]
      }
      if (key === 'bikeTags') {
        data.form[key] = params[key].split(',')
      }
      if (params.detailParams) {
        data.bikeBodyParams = JSON.parse(params.detailParams).bikeBody
        data.wheelGroupParams = JSON.parse(params.detailParams).wheelGroup
        data.variableSpeedParams = JSON.parse(params.detailParams).variableSpeedTransmission
        data.assemblyParams = JSON.parse(params.detailParams).assembly
      }
    }

  })
}

const getBrandList = (query?: string) => {
  getBrandListApi({name: query}).then((res) => {
    if (res.status === 0) {
      data.brandSelectOptions = res.data.pageData.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    }
  })
}

const remoteMethod = (query: string) => {
  if (query) {
    getBrandList(query)
  }
}

const addParams = (type) => {
  if (type === 'bikeBody') {
    if (!isBikeBodyEmpty.value) {
      data.bikeBodyParams.push({
        name: '',
        content: '',
        uid: Math.random().toString().slice(15)
      })
    } else {
      $message.warning('请填写数据再添加')
    }
  } else if (type === 'wheelGroup') {
    if (!isWheelGroupEmpty.value) {
      data.wheelGroupParams.push({
        name: '',
        content: '',
        uid: Math.random().toString().slice(15)
      })
    } else {
      $message.warning('请填写数据再添加')
    }
  } else if (type === 'variableSpeed') {
    if (!isVariableSpeedEmpty.value) {
      data.variableSpeedParams.push({
        name: '',
        content: '',
        uid: Math.random().toString().slice(15)
      })
    } else {
      $message.warning('请填写数据再添加')
    }
  } else if (type === 'assembly') {
    if (!isAssemblyEmpty.value) {
      data.assemblyParams.push({
        name: '',
        content: '',
        uid: Math.random().toString().slice(15)
      })
    } else {
      $message.warning('请填写数据再添加')
    }
  }
}

const deleteParams = (uid: string, type: string) => {
  if (type === 'bikeBody') {
    data.bikeBodyParams = data.bikeBodyParams.filter((item) => {
      return uid !== item.uid
    })
  } else if (type === 'wheelGroup') {
    data.wheelGroupParams = data.wheelGroupParams.filter((item) => {
      return uid !== item.uid
    })
  } else if (type === 'variableSpeed') {
    data.variableSpeedParams = data.variableSpeedParams.filter((item) => {
      return uid !== item.uid
    })
  } else if (type === 'assembly') {
    data.assemblyParams = data.assemblyParams.filter((item) => {
      return uid !== item.uid
    })
  }

}

const submitBefore = (params) => {
  console.log(isBikeBodyEmpty.value, isWheelGroupEmpty.value, isVariableSpeedEmpty.value, isAssemblyEmpty.value)
  if (isBikeBodyEmpty.value || isWheelGroupEmpty.value || isVariableSpeedEmpty.value || isAssemblyEmpty.value) {
    $message.warning('请填写详细参数再提交')
    return false
  }
  const bikeBody = data.bikeBodyParams
  const wheelGroup = data.wheelGroupParams
  const variableSpeedTransmission = data.variableSpeedParams
  const assembly = data.assemblyParams
  params.detailParams = JSON.stringify({
    bikeBody,
    wheelGroup,
    variableSpeedTransmission,
    assembly
  })
  if (data.form.bikeTags.length > 0) {
    params.bikeTags = data.form.bikeTags.join(',')
  }
  console.log(params)
  return true
}

watch(() => data.form.img, () => {
  formPanelRef.value.validateField('img')
})

let isBikeBodyEmpty: any = computed(() => {
  const res = data.bikeBodyParams.filter(item => {
    return item.name === '' || item.content === ''
  })
  return res.length > 0
})

let isWheelGroupEmpty: any = computed(() => {
  const res = data.wheelGroupParams.filter(item => {
    return item.name === '' || item.content === ''
  })
  return res.length > 0
})

let isVariableSpeedEmpty: any = computed(() => {
  const res = data.variableSpeedParams.filter(item => {
    return item.name === '' || item.content === ''
  })
  return res.length > 0
})

let isAssemblyEmpty: any = computed(() => {
  const res = data.assemblyParams.filter(item => {
    return item.name === '' || item.content === ''
  })
  return res.length > 0
})

</script>

<script lang="ts">
export default {
  name: 'bikeForm' // 设置组件名称
};
</script>

<style scoped lang="scss">
.bikeForm {
  .box {
    .bottom {
      width: 85%;
      display: flex;
      flex-wrap: wrap;
      margin-top: 10px;
    }

    .paramsInput {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin-bottom: 10px;
      margin-right: 40px;
    }
  }

  :deep(.el-form) {
    .el-form-item__label {
      width: 120px !important;
    }
  }

}
</style>
